# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from utils.views import WdListCreateAPIView, WdRetrieveUpdateAPIView, WdDestroyAPIView, WdListAPIView, WdAPIView
from models import ResourceManagement, PlayingQueue, PlayingQueueMaterial, AuthorityCodePlayingQueueRelation, \
    ResourceManagementPlayingQueueMaterialRelation
from serializer import ResourceManagementListSerializer, ResourceManagementSerializer, ResourceManagementDetailSerializer, \
    PlayingQueueListSerializer, PlayingQueueSerializer, PlayingQueueDetailSerializer, PlayingQueueMaterialListSerializer, \
    PlayingQueueMaterialSerializer, PlayingQueueMaterialDetailSerializer, ResourceManagementPartialSerializer, \
    AuthorityCodeSerializer
import os
from ElevatorAdmin.settings import MEDIA_ROOT
from utils.response import ErrorCode, general_json_response
from manufacturer.models import AuthorityCode
from rest_framework import status, exceptions


class ResourceManagementListCreateView(WdListCreateAPIView):

    model = ResourceManagement
    serializer_class = ResourceManagementListSerializer
    p_serializer_class = ResourceManagementSerializer
    FILTER_FIELDS = ("rtype", "ttype", "play_mode")
    SEARCH_FIELDS = ("name", )

    def perform_create(self, serializer):
        super(ResourceManagementListCreateView, self).perform_create(serializer)
        obj = self.create_obj
        if obj.file:
            path = obj.file.split("/")[-1]
            path = MEDIA_ROOT + "/" + path
            size = os.path.getsize(path) / 1024
            obj.file_size = size
            obj.save()

    def qs_filter(self, qs):
        qs = super(ResourceManagementListCreateView, self).qs_filter(qs)
        file_min = self.request.GET.get("file_min", None)
        file_max = self.request.GET.get("file_max", None)
        if file_min:
            qs = qs.filter(file_size__gte=int(file_min))
        if file_max:
            qs = qs.filter(file_size__lte=int(file_max))
        return qs


class ResourceManagementDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):

    model = ResourceManagement
    serializer_class = ResourceManagementDetailSerializer
    p_serializer_class = ResourceManagementSerializer

    def perform_update(self, serializer):
        super(ResourceManagementDetailView, self).perform_update(serializer)
        obj = self.get_object()
        if obj.file:
            path = obj.file.split("/")[-1]
            path = MEDIA_ROOT + "/" + path
            size = os.path.getsize(path) / 1024
            obj.file_size = size
            obj.save()


class PlayingQueueListCreateView(WdListCreateAPIView):

    model = PlayingQueue
    p_serializer_class = PlayingQueueSerializer
    serializer_class = PlayingQueueListSerializer
    FILTER_FIELDS = ("ttype", "qtype")
    SEARCH_FIELDS_FOREACH = ("name", "qdesc", "create_user", "update_user")

    def post_check_parameter(self, kwargs):
        code = super(PlayingQueueListCreateView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        user = self.request.user
        self.request.data.update({"create_user": user.username, "update_user": user.username})
        return code


class PlayingQueueDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):

    model = PlayingQueue
    p_serializer_class = PlayingQueueSerializer
    serializer_class = PlayingQueueDetailSerializer

    def perform_update(self, serializer):
        super(PlayingQueueDetailView, self).perform_update(serializer)
        obj = self.get_object()
        user = self.request.user
        obj.update_user = user.username
        obj.save()


class PlayingQueueMaterialListCreateView(WdListCreateAPIView):

    model = PlayingQueueMaterial
    p_serializer_class = PlayingQueueMaterialSerializer
    serializer_class = PlayingQueueMaterialListSerializer
    GET_CHECK_REQUEST_PARAMETER = ("play_queue", )
    POST_CHECK_REQUEST_PARAMETER = ("play_queue", )
    FILTER_FIELDS = ("pqtype", )

    def perform_create(self, serializer):
        super(PlayingQueueMaterialListCreateView, self).perform_create(serializer)
        resource_id = self.request.data.get("resource_id", None)
        obj = self.create_obj
        if resource_id:
            ResourceManagementPlayingQueueMaterialRelation.objects.create(material=obj, resource_id=resource_id)
        user = self.request.user
        if obj.play_queue:
            obj.pqtype = obj.play_queue.qtype
        obj.create_user = user.username
        obj.update_user = user.username
        obj.save()


class PlayingQueueMaterialDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):

    model = PlayingQueueMaterial
    p_serializer_class = PlayingQueueMaterialSerializer
    serializer_class = PlayingQueueMaterialDetailSerializer

    def perform_update(self, serializer):
        super(PlayingQueueMaterialDetailView, self).perform_update(serializer)
        obj = self.get_object()
        resource_id = self.request.data.get("resource_id", None)
        if resource_id:
            ResourceManagementPlayingQueueMaterialRelation.objects.update_or_create(material=obj, defaults={"resource_id": resource_id})
        if obj.play_queue:
            obj.pqtype = obj.play_queue.qtype
        user = self.request.user
        obj.update_user = user.username
        obj.save()


class QueryResourceListView(WdListAPIView):
    model = ResourceManagement
    serializer_class = ResourceManagementPartialSerializer
    GET_CHECK_REQUEST_PARAMETER = ("play_mode", )
    FILTER_FIELDS = ("play_mode", )


class ResourceManagementPlayingQueueMaterialRelationView(WdAPIView):

    def post(self, request, *args, **kwargs):
        material = self.request.data.get("material", None)
        resource = self.request.data.get("resource", None)
        retention_time = self.request.data.get("retention_time", None)
        ResourceManagementPlayingQueueMaterialRelation.objects.create(material_id=material, resource_id=resource, retention_time=retention_time)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)

    def delete(self, request, *args, **kwargs):
        ids = self.request.data.get("ids", [])
        ResourceManagementPlayingQueueMaterialRelation.objects.filter_active(id__in=ids).update(is_active=False)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class AuthorityCodeListView(WdListAPIView):

    model = AuthorityCode
    serializer_class = AuthorityCodeSerializer
    GET_CHECK_REQUEST_PARAMETER = ("play_queue", )
    SEARCH_FIELDS_FOREACH = ("device_code_elevator", "property_company_name", "address", "elevator_code")

    def qs_filter(self, qs):
        qs = super(AuthorityCodeListView, self).qs_filter(qs)
        play_queue = self.request.GET.get("play_queue", None)
        allocated = self.request.GET.get("allocated", None)
        acs = AuthorityCodePlayingQueueRelation.objects.filter_active(play_queue_id=play_queue).values_list(
            "authority_code_id", flat=True).distinct()
        if allocated:
            qs = qs.filter(id__in=acs)
        else:
            qs = qs.exclude(id__in=acs)
        return qs


class AuthorityCodePlayingQueueRelationApiView(WdAPIView):

    def post(self, request, *args, **kwargs):
        relation = self.request.data.get("relation", [])
        play_queue = self.request.data.get("play_queue", None)
        bulk_list = list()
        acs = AuthorityCodePlayingQueueRelation.objects.filter_active(play_queue_id=play_queue).values_list("authority_code_id", flat=True).distinct()
        for acpqr in relation:
            if acpqr in acs:
                continue
            ac = AuthorityCode.objects.filter_active(id=acpqr).first()
            if ac:
                dic = {"authority_code_id": acpqr, "play_queue_id": play_queue}
                bulk_list.append(AuthorityCodePlayingQueueRelation(**dic))
        if bulk_list:
            AuthorityCodePlayingQueueRelation.objects.bulk_create(bulk_list)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)

    def delete(self, request, *args, **kwargs):
        relation = self.request.data.get("relation", [])
        play_queue = self.request.data.get("play_queue", None)
        AuthorityCodePlayingQueueRelation.objects.filter_active(authority_code_id__in=relation, play_queue_id=play_queue).update(is_active=False)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)





















































